package mashibing.class12;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 是否为完全二叉树
 *
 * @author yujiafan
 * @version 1.0.0
 * @create 2023-05-18
 */
public class Class12_1_IsCBT {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    public static boolean isCBT1(Node root){
        if(root == null){
            return true;
        }
        // 按层遍历
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        // 是否遍历到叶子节点
        boolean leaf = false;
        Node left = null;
        Node right = null;
        while (!queue.isEmpty()){
            Node poll = queue.poll();
            left = poll.left;
            right = poll.right;
            // 不满足完全二叉树：1、无左树有右树，2、当一个节点无孩子是，接下来的节点都是叶子节点
            if((left == null && right != null) || (leaf && (left != null || right != null))){
                return false;
            }
            if(left != null){
                queue.add(left);
            }
            if(right != null){
                queue.add(right);
            }
            // 是否为叶子节点
            if(left == null || right == null){
                leaf = true;
            }
        }
        return true;
    }

    // for test
    public static Node generateRandomBST(int maxLevel, int maxValue) {
        return generate(1, maxLevel, maxValue);
    }

    // for test
    public static Node generate(int level, int maxLevel, int maxValue) {
        if (level > maxLevel || Math.random() < 0.5) {
            return null;
        }
        Node head = new Node((int) (Math.random() * maxValue));
        head.left = generate(level + 1, maxLevel, maxValue);
        head.right = generate(level + 1, maxLevel, maxValue);
        return head;
    }

//    public static void main(String[] args) {
//        int maxLevel = 5;
//        int maxValue = 100;
//        int testTimes = 1000000;
//        for (int i = 0; i < testTimes; i++) {
//            Node head = generateRandomBST(maxLevel, maxValue);
//            if (isCBT1(head) != isCBT2(head)) {
//                System.out.println("Oops!");
//            }
//        }
//        System.out.println("finish!");
//    }


}
